#!/usr/bin/env python
# coding=utf-8
# __author__ = 'Yunchao Ling'

from pymongo import MongoClient


# 连接MongoDB
def InitMongoDB(MONGODB_HOST, MONGODB_PORT, MONGODB_DB_NAME, MONGODB_COLLECTION_NAME):
    client = MongoClient(MONGODB_HOST, MONGODB_PORT)
    db = client[MONGODB_DB_NAME]
    collection = db[MONGODB_COLLECTION_NAME]
    return client, collection


# 关闭MongoDB
def CloseMongoDB(MongoDB_Connection):
    MongoDB_Connection.close()


def GetHPORoots(depth: int):
    print("hpo_id\tparent_id\thpo_name\tchpo_name")

    current_ids = ["0000001"]
    next_ids = ["0000001"]
    HPO_client, HPO_collection = InitMongoDB("10.188.188.22", 27017, "Dictionary", "HumanPhenotypeOntology_20171005")
    CHPO_client, CHPO_collection = InitMongoDB("10.188.188.22", 27017, "Pre_Data", "ChinaHPO")

    for current_id in current_ids:
        result = HPO_collection.find_one({"dms_id": current_id}, {"_id": 0, "dms_id": 1, "is_a": 1, "dms_name": 1})
        result2 = CHPO_collection.find_one({"hpoId": "HP:" + current_id}, {"_id": 0, "name_cn": 1})
        print_word = "HP:" + result["dms_id"] + "\tHP:0000001\t" + result["dms_name"]
        if result2 != None:
            print(print_word + "\t" + result2["name_cn"])
        else:
            print(print_word + "\t")

    for i in range(depth):
        print()
        current_ids = next_ids
        next_ids = []
        for current_id in current_ids:
            results = HPO_collection.find({"is_a.id": current_id}, {"_id": 0, "dms_id": 1, "is_a": 1, "dms_name": 1})
            for result in results:
                next_ids.append(result["dms_id"])
                result2 = CHPO_collection.find_one({"hpoId": "HP:" + result["dms_id"]}, {"_id": 0, "name_cn": 1})
                print_word = "HP:" + result["dms_id"] + "\tHP:" + current_id + "\t" + result["dms_name"]
                if result2 != None:
                    print(print_word + "\t" + result2["name_cn"])
                else:
                    print(print_word + "\t")
    CloseMongoDB(HPO_client)
    CloseMongoDB(CHPO_client)


if __name__ == '__main__':
    GetHPORoots(3)
